const App = getApp();
var WxParse = require('../../wxParse/wxParse.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    teamList:[],
    team_id:0,//服务队ID
    examine_status:"",//审核状态
    show_status:true,//是否提示正在审核（提示一次关闭）
    popupStatus:false,
    scrollHeight: null,
    detail:{},
    family:"",
    gender:"",
    birth_date:"",
    address:"",
    cate:1,
    detail2:{},
    category:"",
    political:"",
    military:"",
    career:"",
    criminal:"",
    fileList:[],
    notice:""
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options){
    this.getNotice()
    this.getTeamList()
  },
  onShow(options){
    this.setListHeight()
    // that.getData()
  },
  // tab切换
  onChangeNews(e){
    let that = this;
    that.setData({
      cate: e.currentTarget.dataset.id,
    }); 
    that.getData()
  },
  /**
   * 填表须知
   */
  getNotice() {
    App._get('user.index/addMember', {}, result => {
      WxParse.wxParse('notice', 'html', result.data, this,5);   
    });
  },
  //获取服务队列表
  getTeamList(){
    App._get('user.index/teamInfo', {}, result => {
      this.setData({
        teamList: result.data
      })
      this.getData()
    });
  },
  //如果已经申请过，查询数据
  getData(){
    let that = this
    App._get('user.index/myApplyFor', {}, result => {
      let detail = result.data.data,detail2 =result.data.second_data
      if(detail){
        let fileList = []
        fileList.push({
          url: detail.image_a,
          file_id:detail.carda_id,
        });
        fileList.push({
          url: detail.image_b,
          file_id:detail.cardb_id,
        });
        that.setData({
          detail,
          team_id:detail.team_id,
          family: detail.family,
          gender: detail.gender,
          birth_date: detail.birth_date,
          examine_status: detail.examine_status,
          address: detail.address,
          fileList,
          detail2,
          category:typeof(detail2.category)=="undefined"?"":detail2.category,
          political:typeof(detail2.political)=="undefined"?"":detail2.political,
          military:typeof(detail2.military)=="undefined"?"":detail2.military,
          career:typeof(detail2.career)=="undefined"?"":detail2.career,
          criminal:typeof(detail2.criminal)=="undefined"?"":detail2.criminal,
        })
        //计算服务队KEY
        let arr = that.data.teamList;
        arr.filter(function(item,key){
          if(item.team_id == detail.team_id){
            that.setData({
              index:key
            })
          }
        })
        //判断是否已经通过审核
        if(that.data.examine_status === 1){
          App.showSuccessToast("会员已通过审核", function() {
            wx.navigateTo({
              url: '/pages/member/login',
            })
          });
        }
        if(that.data.examine_status === 2 && that.data.cate == 1){
          App.showError("您得审核被驳回："+that.data.detail.examine_remark);
        }
        if(that.data.examine_status === 0 && that.data.show_status){
          App.showSuccess("您的申请正在审核中，您可以继续补充入会资料。", function() {
            that.setData({
              show_status:false
            })
          });
        }
      }
    });
  },
  /**
   * 表单提交(必填项)
   */
  onsumbit(e) {
    let formData = e.detail.value;
    formData.family=this.data.family;
    formData.birth_date=this.data.birth_date;
    formData.gender=this.data.gender;
    formData.team_id=this.data.team_id;
    formData.address=this.data.address;
    let formStatus = false
    for (let key in formData) {
      if(formData[key] === ""){
        console.log(key)
        formStatus = true
        break;
      }
    }
    if(formStatus){
      App.showError("申请信息不全，所有项必填！");
      return;
    }
    // 身份证
    if(this.data.fileList.length<2){
      App.showError("身份证正反面必填！");
      return;
    }
    formData.carda_id = this.data.fileList[0].file_id;
    formData.cardb_id = this.data.fileList[1].file_id;
    App._post_form('user.index/applyFor', formData, result => {
      //成功提示
      App.showSuccess(result.msg, function() {});
    });
  },
  /**
   * 表单提交(选填项)
   */
  onsumbit2(e) {
    let formData = e.detail.value;
    formData.category=this.data.category;
    formData.political=this.data.political;
    formData.military=this.data.military;
    formData.career=this.data.career;
    formData.criminal=this.data.criminal;
    App._post_form('user.index/applyForSecondary  ', formData, result => {
      //成功提示
      App.showSuccess(result.msg, function() {});
    });
  },
  //选择器(radio\checkbox\日期)
  radioChange(e) {
    console.log('change事件，携带value值为：', e.detail.value)
    let type = e.currentTarget.dataset.type;
    this.setData({
      [type]: e.detail.value
    })
  },
  //获取微信地址
  chooseLocation(){
    wx.chooseLocation({
      success: (res) => {
        if(res.address!='' && res.name!=''){
          this.setData({
            address:res.address,
          })
        }
        return false;
      },
    })
  },
  //选择服务队
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index:e.detail.value,
      team_id:this.data.teamList[e.detail.value].team_id,
    })
    
  },
  // 导航更多开关
  popup(e){
    let that = this;
    that.setData({
      popupStatus: !that.data.popupStatus
    }); 
  },
  //设置文章列表高度
  setListHeight() {
    let systemInfo = wx.getSystemInfoSync(),
      rpx = systemInfo.windowWidth / 750, // 计算rpx
      tapHeight = Math.floor(rpx * 120), // tap高度
      scrollHeight = systemInfo.windowHeight - tapHeight; // swiper高度
      console.log(systemInfo.windowHeight,scrollHeight);
      this.setData({
        scrollHeight
      });
  },
  // 删除照片
  deleteClick(event) {
    var imgData = this.data.fileList;
    // 通过splice方法删除图片
    imgData.splice(event.detail.index, 1);
    // 更新图片数组
    this.setData({
        fileList: imgData
    })
    console.log(this.data.fileList)
  },
  // 图片上传
  afterRead(event) {
    let that = this;
    // loading加载
    wx.showLoading({title: '上传中...'});
    //获取图片详细信息
    const {file} = event.detail;
    //调用上传图片方法
    that.uploadCompressImg(file).then(res=>{
      App.uploadFile(res,{},function(result){
        const fileList = that.data.fileList;
        // // 将图片信息添加到fileList数字中
        fileList.push({
            url: result.data.file_path,
            file_id:result.data.file_id,
        });

        // 更新存放图片的数组
        that.setData({
            fileList
        });
         wx.hideLoading();//停止loading
      })
    })

  },
  //图片压缩
  uploadCompressImg(file) {
    let that = this
    return new Promise(function(resolve, reject){
      let file_url = file.tempFilePath
      console.log(file);
      if(file.size < 500*1024){
        console.log("size",file.size)
        console.log("file_url",file_url)
        resolve(file_url);
      }else{
          // 获得原始图片大小
          wx.getImageInfo({
            src: file_url,
            success(res) {
              console.log(res);
            
              let originHeight = res.height;
              let originWidth = res.width;
              // 压缩比例
              // 最大尺寸限制
              let maxWidth = 1024,
                maxHeight = 1024;
              // 目标尺寸
              let targetWidth = originWidth,
                targetHeight = originHeight;
              // 等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              // 更新 canvas 大小
              that.setData({
                "cw": targetWidth,
                "ch": targetHeight
              });
              // 尝试压缩文件，创建 canvas
              let ctx = wx.createCanvasContext('canvas');
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              //通过得到图片旋转的角度来调整显示方向以正确显示图片，主要解决 ios 系统上的图片会有旋转的问题
              let orientation = res.orientation;
              if (orientation == 'right') { //exif的6
                that.setData({
                  "cw": targetHeight,
                  "ch": targetWidth
                });
                ctx.rotate(90 * Math.PI / 180);
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight, 0, -targetHeight, that.data.ch, that.data.cw);
              } else {
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight);
              }

              ctx.draw(false, function () {
                // 获得新图片输出
                wx.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: 'canvas',
                  destWidth: targetWidth,
                  destHeight: targetHeight,
                  quality: 0.9,
                  fileType: "jpg",
                  success: (res) => {
                    console.log(res)
                    resolve(res.tempFilePath);
                  },
                  fail: (err) => {
                    console.error(err)
                  }
                }, this)
              })
            }
          })
      }
    })
  },

})